import time
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver import ActionChains
# from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait

from page.basepage import BasePage
from selenium.webdriver.common.by import By


# page/login_page.py
class SubmitPage(BasePage):
    def __init__(self,driver):
        super().__init__(driver)
        self.title_input = (By.CSS_SELECTOR, 'input[placeholder="请在这里输入标题"]')
        # self.text_input = (By.CSS_SELECTOR, '.el-dialog__wrapper textarea.el-textarea__inner')
        self.text_input_btn = (By.XPATH, '//li[@title="添加文字"]')
        self.inner_text_input = (By.CSS_SELECTOR, 'textarea.el-textarea__inner')
        self.image_input_btn = (By.XPATH, '//li[@title="添加图片"]')
        self.time_el = (By.CSS_SELECTOR, 'input[placeholder="请选择日期时间"]')
        self.time_enter = (By.CSS_SELECTOR, '.el-button.el-picker-panel__link-btn.el-button--default')
        self.text_input = (By.XPATH, '//div[text()="请在这里输入正文"]')
        self.image_confirm = (By.XPATH, '//*[@id="app"]/div/div[2]/section/div/div/div/div[3]/span/button[2]')
        self.confirm_btn = (By.XPATH, '//span[text()="确定"]/..')
        self.submit_page = "http://localhost:8802/#/article/publish"
        self.tag_input = (By.CSS_SELECTOR,'input[placeholder="请输入标签"]')
        self.btn_submit = (By.XPATH, '//span[contains(text(),"提交审核")]')
        self.choose_pic_ok_btn = (By.CSS_SELECTOR, '.el-dialog__wrapper:not([style*="display: none"]) .el-dialog__footer .el-button--success')
        self.dropdown_channel = (By.CSS_SELECTOR, '.el-input__inner[readonly]')
        self.get_channel = (By.XPATH, "//li[@class='el-select-dropdown__item']/span")


    def add_text_block(self, content):
        if len(content) == 0:
            return
        hover_target = self.find(self.text_input)

        # 2. 悬停操作
        ActionChains(self.driver).move_to_element(hover_target).perform()
        # 1. 点击“添加文字”按钮
        add_text_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.text_input_btn)
        )
        add_text_button.click()

        # 2. 输入正文内容
        textarea = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located(self.inner_text_input)
        )
        textarea.send_keys(content)

        # 3. 点击“确定”按钮
        confirm_button = self.find(self.confirm_btn)
        confirm_button.click()

    def goto_submit_page(self):
        self.driver.get(self.submit_page)


    def add_images_block_by_index(self,index):
        if len(index) == 0:
            return
        hover_target = self.find(self.text_input)

        # 2. 悬停操作
        ActionChains(self.driver).move_to_element(hover_target).perform()
        # time.sleep(1)
        # 1. 点击“添加图片”按钮

        add_btn = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.image_input_btn)
        )
        # 强制点击
        self.driver.execute_script("arguments[0].click();", add_btn)
        # time.sleep(1)
        imagearea = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, f'.img_list:nth-child({index}) img'))
        )

        imagearea.click()
        #
        # # 3. 点击“确定”按钮
        confirm_button = self.find(self.image_confirm)
        confirm_button.click()


    def input_text(self, text):
        textarea = self.find(self.inner_text_input)
        textarea.send_keys(text)

    def input_tag(self,text):
        if len(text) == 0:
            return
        self.find(self.tag_input).send_keys(text)


    def choose_pic_by_index(self, idx,css):
        """
        idx: 1 第一个 | 2 第二个 | 3 第三个
        """
        # 1) 等弹窗消失（如果弹窗有“关闭”按钮，可提前关闭）
        time.sleep(1)

        # 2) 找到按钮

        btn = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, css))
        )
        btn.click()
        time.sleep(2)
        pic = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, f'.img_list_con .img_list:nth-child({idx})'))
        )
        pic.click()
        time.sleep(1)
        confirm = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.choose_pic_ok_btn)
        )
        confirm.click()

    def select_cover(self, num,idx):
        if len(num) == 0:
            return
        """
            value: 1 单图 | 3 三图 | 0 无图 | -1 自动
            """
        num = int(num)
        idx = int(idx)
        label_xpath = f'//label[.//input[@value="{num}"]]'
        self.find((By.XPATH, label_xpath)).click()
        time.sleep(2)
        if num == 1:
            css = '.single_pic'
            self.choose_pic_by_index(idx, css)
        elif num == 3:
            for i in range(1,idx+1):
                css = f'.three_pic .three_pic_item:nth-child({i})'
                self.choose_pic_by_index(i,css)

    def input_title(self, title):
        if len(title) == 0:
            return
        self.input(self.title_input,title)

    def submit(self):
        btn = self.find(self.btn_submit)
        # print(f"按钮是否可见: {btn.is_displayed()}")
        # print(f"按钮是否可点击: {btn.is_enabled()}")
        # print(f"按钮是否被遮挡: {self.driver.execute_script('return arguments[0].checkVisibility()', btn)}")
        # 如果按钮被禁用，等待状态改变
        if not btn.is_enabled():
            WebDriverWait(self.driver, 10).until(
                lambda d: d.find_element(*self.btn_submit).is_enabled()
            )

        # JavaScript点击
        self.driver.execute_script("arguments[0].click();", btn)

    def choose_time_now(self):
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.time_el)
        ).click()
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.time_enter)
        ).click()

    # def choose_time_now(self):
    #     time.sleep(1)
    #     el = self.find(self.time_el)
    #     el.click()
    #     time.sleep(0.5)
    #     accept = WebDriverWait(self.driver, 10).until(
    #         EC.element_to_be_clickable(
    #             self.time_enter
    #         )
    #     )
    #     accept.click()
    #     time.sleep(1)

    def select_channel(self, channel_name):
        if len(channel_name) == 0:
            return
        # time.sleep(1)
        dropdown_input = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.dropdown_channel)
        )
        dropdown_input.click()
        time.sleep(0.5)
        # 先获取所有频道元素
        options = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.get_channel)
        )

        # 找到目标频道的位置（索引+1，因为列表索引是0开始）
        target_index = None
        for idx, opt in enumerate(options, start=1):
            # print("opt.text.strip() = ",opt.text.strip())
            if opt.text.strip() == channel_name:
                target_index = idx
                break

        if target_index is None:
            raise ValueError(f"频道 '{channel_name}' 不存在")

        # 点击目标频道
        options[target_index - 1].click()
        return target_index-5



